<?php
namespace app\worker;
use GatewayWorker\Lib\Gateway;
use think\Db;
class Events
{
    
    public static function onWorkerStart($businessWorker){
		Db::name("user")->where("1=1")->update(["is_online"=>0,"update_time"=>time()]);
    }
    
   
 
	    /**
	    * 有消息时
	    * @param int $client_id
	    * @param mixed $message
	    */
	   public static function onMessage($client_id, $message)
	   {
	   		
	   		$message_data = json_decode($message, true);
	        if(!$message_data)
	        {
	            return ;
	        }
	        
	        //判断进入状态
	        switch($message_data['type'])
        	{
	            case 'pong':
	                return;
	            case 'login':
	            	$user_id=$message_data["user_id"];
	            	$_SESSION["user_id"]=$user_id;
	            	Gateway::bindUid($client_id,$user_id);
	            	Db::name("user")->where(['id'=>$user_id])->update(["is_online"=>1,"update_time"=>time()]);
	            	Gateway::sendToCurrentClient(json_encode(["type"=>"login","msg"=>"登陆成功"]));
	            	return;
	        }
	   		
	   	
	   }

	  
	   /**
	    * 当客户端断开连接时
	    * @param integer $client_id 客户端id
	    */
	   public static function onClose($client_id)
	   {
	   		$user_id=$_SESSION["user_id"];
	   		Db::name("user")->where(['id'=>$user_id])->update(["is_online"=>0,"update_time"=>time()]);
	   }
}